package com.cc.blog.web.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cc.blog.admin.mapper.ArticleMapper;
import com.cc.blog.admin.mapper.CategoryMapper;
import com.cc.blog.admin.mapper.TagMapper;
import com.cc.blog.admin.model.ArticleDO;
import com.cc.blog.common.utils.Result;
import com.cc.blog.web.domain.vo.FindStatisticsInfoRspVO;
import com.cc.blog.web.service.StatisticsService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author cc
 * @Date 2024/7/26 13:59
 */
@Service
@Slf4j
@AllArgsConstructor
public class StatisticsServiceImpl implements StatisticsService {

    private final ArticleMapper articleMapper;
    private final CategoryMapper categoryMapper;
    private final TagMapper tagMapper;

    @Override
    public Result findInfo() {
        // 查询文章总数
        Long articleTotalCount = articleMapper.selectCount(Wrappers.emptyWrapper());
        // 查询分类总数
        Long categoryTotalCount = categoryMapper.selectCount(Wrappers.emptyWrapper());
        // 查询标签总数
        Long tagTotalCount = tagMapper.selectCount(Wrappers.emptyWrapper());
        // 总浏览量
        List<ArticleDO> articleDOS = articleMapper.selectList(Wrappers.<ArticleDO>lambdaQuery().select(ArticleDO::getReadNum));
        Long pvTotalCount = 0L;
        if (!CollectionUtils.isEmpty(articleDOS)) {
            // 所有 read_num 相加
            pvTotalCount = articleDOS.stream().mapToLong(ArticleDO::getReadNum).sum();
        }
        // 组装 VO 类
        FindStatisticsInfoRspVO vo = FindStatisticsInfoRspVO.builder()
                .articleTotalCount(articleTotalCount)
                .categoryTotalCount(categoryTotalCount)
                .tagTotalCount(tagTotalCount)
                .pvTotalCount(pvTotalCount)
                .build();

        return Result.success(vo);
    }
}
